#include <QTimerEvent>
#include <QPainter>

#include "UIBatteryView.h"
#include "UIDevice.h"

class UIBatteryViewPrivate {
    public:
        int timerId;
};

UIBatteryView::UIBatteryView (QGraphicsItem *parent) 
    : QObject(), UIView(parent), d(new UIBatteryViewPrivate)
{
    d->timerId = startTimer(1000);
}

UIBatteryView::~UIBatteryView() {
    killTimer(d->timerId);
    delete d;
}

void UIBatteryView::drawRect (QPainter *painter, const QRect& rect) {
    UIDevice *device = UIDevice::currentDevice();
    qreal level = device->batteryLevel();

    painter->save();
    painter->setPen(QColor(0x3b, 0x44, 0x5a));

    QLinearGradient batteryGradient(rect.x(), rect.y(), 0, rect.height());
    batteryGradient.setColorAt(0.0f, QColor(0x70, 0xd8, 0x3a));
    batteryGradient.setColorAt(0.5f, QColor(0xa1, 0xf5, 0x63));
    batteryGradient.setColorAt(0.6f, QColor(0x61, 0xca, 0x29));
    batteryGradient.setColorAt(1.0f, QColor(0x3a, 0x9e, 0x17));

    QLinearGradient batteryNoGradient(rect.x(), rect.y(), 0, rect.height());
    if (level < 0.2f) {
        batteryNoGradient.setColorAt(0.0f, QColor(0xa2, 0x02, 0x02));
        batteryNoGradient.setColorAt(1.0f, QColor(0xff, 0x0f, 0x0f));
    } else {
        batteryNoGradient.setColorAt(0.0f, QColor(0x52, 0x52, 0x52));
        batteryNoGradient.setColorAt(1.0f, QColor(0xbf, 0xbf, 0xbf));
    }

    int availWidth = (int)(rect.width() * level);
    painter->fillRect(rect.x(), rect.y(), 
                      availWidth, rect.height(), 
                      batteryGradient);
    painter->fillRect(rect.x() + availWidth, rect.y(), 
                      rect.width() - availWidth, rect.height(), 
                      batteryNoGradient);
    painter->drawRect(rect.x(), rect.y(), rect.width(), rect.height());
    painter->fillRect(rect.x() + rect.width(), rect.y() + 2,
                      3, rect.height() - 4,
                      batteryNoGradient);

    painter->restore();
}

void UIBatteryView::timerEvent (QTimerEvent *event) {
    if (d->timerId == event->timerId()) {
        update();
    } else {
        QObject::timerEvent(event);
    }
}

